package bookez.view.bean.backing;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.xml.bind.ValidationException;

import bookez.model.businessobject.BusType;
import bookez.model.exception.BusinessLogicLayerException;
import bookez.view.bean.BusTypeBean;
import bookez.view.util.FacesUtil;
import bookez.view.util.ProcessMessage;

@ManagedBean
@SessionScoped
public class BusTypeForm extends BaseBackingBean {

	
	public void createBusType() {
		
		BusType newType = BusTypeBean.createBusType( getModel() );
		
		try {
			boolean isSaved = getModel().getService().createBusType( newType );
			
			if( isSaved ) { 
				ProcessMessage.processInfo( formMessage.getClientId( FacesUtil.getFacesContext() ),
											BusTypeBean.TYPE_CREATED,
											new Object[] { newType.getName() } );
			}//end if
		}//end try
		
		catch ( BusinessLogicLayerException e ) {
			ProcessMessage.processError( getFormMessage().getClientId( FacesUtil.getFacesContext() ),
										 BusTypeBean.CANNOT_CREATE,
										 new Object[] { newType.getName() } );
			e.printStackTrace();
		}//end catch
		
	}//end method createBusType
	

	
	/*-----------------------------------------------
	 * 	Properties
	 *----------------------------------------------*/
	
	public UIInput getNameInput() { return this.nameInput; }
	public void setNameInput( UIInput value ) { this.nameInput = value; }
	
	public UIInput getSeatTypeInput() { return seatType; }
	public void setSeatTypeInput(UIInput seatType) { this.seatType = seatType; }
	
	public UIInput getSeatCountInput() {	return seatCount; }
	public void setSeatCountInput(UIInput seatCount) { this.seatCount = seatCount; }
	
	public void setFormMessage(UIMessage formMessage) {this.formMessage = formMessage; }
	public UIMessage getFormMessage() { return formMessage; }

	public BusTypeBean getModel() { return this.model; }
	public void setModel( BusTypeBean value ) { this.model = value; }
	
	public boolean isNewTypeMode() { return this.newTypeMode; }
	public void setNewTypeMode( boolean value ) { this.newTypeMode = value; }
	
	
	/*-----------------------------------------------
	 * Validators
	 * 	- validateName
	 * 	- validateSeatCount
	 *  - validateSeatType
	 *----------------------------------------------*/
	
	/**
	 * Check if the input name is already existing
	 * @param context
	 * @param ui
	 * @param value
	 */
	public void validateName( FacesContext context, UIComponent ui, Object value )
				throws ValidationException {
		boolean textMode = !isNewTypeMode();
		if( textMode ) { return; }
		
		String name = (String) value;
		
		if( name.isEmpty() ) {
			((UIInput)ui).setValid( false );
			ProcessMessage.processError( ui.getClientId( context ), BusTypeBean.NAME_REQUIRED, null );
			//throw new ValidationException( "Name is empty." );
		}//end case: input is empty
		else {
			try {
				BusType result = getModel().getService().getBusTypeByName( name );
				if( result != null ) { 
					((UIInput)ui).setValid( false );
					ProcessMessage.processError( ui.getClientId( context ), BusTypeBean.NAME_EXISTS, new Object[] {name} );
					//throw new ValidationException( "BusType with this name is existing." );
				}//end if
			}//end try
			
			catch (BusinessLogicLayerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//throw new ValidationException( "Something went wrong." );
			}//end catch
		}//end else
		
	}//end validateName
	
	public void validateSeatCount( FacesContext context, UIComponent ui, Object value ) throws ValidationException {
		try {
		Integer seatCount = (Integer) value;
		
		// No need this block, b/c JSF automically convert value to Integer
		/*String seatCountString = (String) value;
		
		Integer seatCount = NumberUtil.parseInt( seatCountString );
		
		if ( seatCount == null ) { 
			( (UIInput)ui ).setValid( false );
			ProcessMessage.processError( ui.getClientId( context ), BusTypeBean.SEAT_COUNT_INCORRECT, null );
			throw new ValidationException( "seatCount has incorrect value." );
		}//end case: seat count is null
		*/
		
		boolean isInRange = (seatCount >= 20) && (seatCount <= 80);
		
		if ( !isInRange ) {
			( (UIInput)ui ).setValid( false );
			ProcessMessage.processError( ui.getClientId( context ), BusTypeBean.SEAT_COUNT_RANGE, null );
			//throw new ValidationException( "seatCount is out of range." );
		}//end case: seatcount is out of range		
		}//end try
		catch (Exception ex ) {
			ex.printStackTrace();
		}
	}//end method validateSeatCount
	
	public void validateSeatType( FacesContext context, UIComponent ui, Object value ) throws ValidationException {
		String seatType = (String) value;
		
		if ( seatType == null )  { 
			( (UIInput)ui ).setValid( false );
			ProcessMessage.processError( ui.getClientId( context ), BusTypeBean.SEAT_COUNT_INCORRECT, null );
			//throw new ValidationException( "seatCount has incorrect value." );
		}//end case: null value
	}//end method 
	
	/*-----------------------------------------------
	 * 	Listeners
	 *----------------------------------------------*/
	
	public void modeChanged( ValueChangeEvent event ) {
		
		setNewTypeMode( (Boolean)event.getNewValue() );
		
		log( "isNewTypeMode = " + isNewTypeMode() );
		getModel().clear();
		//UIComponent comp = event.getComponent().findComponent( "name" );
		
		//comp.clearInitialState();
	}//end method modeChanged
	
	public void busTypeChanged( ValueChangeEvent event ) {
		this.log( "Invoke valueChangeListener");
		//BusType newValue = (BusType) event.getNewValue();
		//loadBusType( newValue );
	}//end method processValueChange
	
/*	private void addValidators() {
		getNameInput().addValidator( nameValidator );
	}//end method addValidators
	
	private void removeValidators() {
		getNameInput().removeValidator( nameValidator );
	}//end method removeValidators
*/	
/*	private BusType buildBusType() {
		
		BusType type = new BusType();
		type.setName( (String) getNameInput().getValue()	);
		
	}//end method createButType
*/	
	/*-----------------------------------------------
	 * 	Instance Variables
	 *----------------------------------------------*/

	private UIInput nameInput;
	private UIInput seatType;
	private UIInput seatCount;
	private UIMessage formMessage;
	
	
	
	//private BusTypeNameValidator nameValidator = new BusTypeNameValidator();
	
	private boolean newTypeMode = true;
	
	@ManagedProperty ( name = "model", value = "#{busTypeBean}")
	private BusTypeBean model;
	
	private static final long serialVersionUID = -7290737702631641662L;
}//end class BusTypeForm
